<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Tasks</title>
</head>
<body>

<h1>My Tasks</h1>

<div id="addTask">
    <form>
        <input type="text" placeholder="Add new task" id="taskTitle">
        <input type="submit" value="Add Task">
    </form>
</div>

<div class="tasks">

</div>

<script type="text/template" id="tpl_task">
    <span><%= title%></span> <button class="edit">Edit</button> <button class="delete">Delete</button>
</script>

<script src="assets/js/lib/zepto.js"></script>
<script src="assets/js/lib/underscore.js"></script>
<script src="assets/js/lib/backbone.js"></script>

<script>
(function () {

    window.App = {

        Models: {},
        Views: {},
        Collections: {},

        init: function () {

            var tasksCollection = new App.Collections.Tasks([
                {
                    title: 'go to work',
                    priority: 2
                },
                {
                    title: 'go to study',
                    priority: 3
                },
                {
                    title: 'go to read',
                    priority: 5
                }
            ]);

            // 初始化添加任务视图
            var addTaskView = new App.Views.AddTask({collection: tasksCollection});

            // 初始化任务列表并显示到网页中
            var tasksView = new App.Views.Tasks({collection: tasksCollection});
            $('.tasks').html( tasksView.render().el );

        }

    };

    // App 走起 - -!
    $( _.bind(App.init, App) );



    // Models - 任务模型
    App.Models.Task = Backbone.Model.extend({
        defaults: {
            title: '',
            priority: 0
        },

        validate: function (attrs) {
            if ( ! $.trim(attrs.title) ) {
                return 'The title can not be empty...';
            }
        }
    });

    // Collections - 任务集合
    App.Collections.Tasks = Backbone.Collection.extend({
        model: App.Models.Task
    });

    // single task - 单个任务视图
    App.Views.Task = Backbone.View.extend({
        tagName: 'li',

        events: {
            'click .edit': 'editTask',
            'click .delete': 'destroy'
        },

        initialize: function () {
            this.model.on('change', this.render, this);
            this.model.on('destroy', this.remove, this);
            this.model.on('invalid', this.invalid, this);
        },

        editTask: function () {
            var newTaskTitle = prompt('What do you want to change?', this.model.get('title'));

            if (!newTaskTitle) return; // 点击 取消 时不做操作

            // 新版 backbone 使用 set 方法时默认不自动进行验证，需添加 {validate: true} 开启
            this.model.set('title', newTaskTitle, {validate: true});
        },

        destroy: function () {
            this.model.destroy();
        },

        remove: function () {
            this.$el.remove();
        },

        invalid: function (model, error) {
            alert(error);
        },

        render: function () {
            var tpl = _.template( $('#tpl_task').html(), this.model.toJSON() );
            this.$el.html(tpl);
            return this;
        }
    });

    // task list - 任务列表
    App.Views.Tasks = Backbone.View.extend({
        tagName: 'ul',

        initialize: function () {
            this.collection.on('add', this.addOne, this);
        },

        render: function () {
            this.collection.each(this.addOne, this);
            return this;
        },

        addOne: function (task) {
            var taskView = new App.Views.Task({model: task});
            this.$el.append(taskView.render().el);
        }
    });

    // add task - 添加新任务视图
    App.Views.AddTask = Backbone.View.extend({
        el: '#addTask',

        events: {
            'submit': 'submit'
        },

        submit: function (e) {
            e.preventDefault(); // 取消表单默认提交事件

            var newTaskTitle = $('#taskTitle').val();
            var task = new App.Models.Task();
            // 对任务标题进行校验设置
            var chk = task.set('title', newTaskTitle, {validate: true});
            if (!chk) {
                alert(task.validationError);
                return;
            };
            this.collection.add(task);

            $('#taskTitle').val(''); // 添加后清空文本域
        }
    });

})();
</script>

</body>
</html>
